// pages/game/voiceRoom/voiceRoom.js
const app = getApp()
var tim = app.imInit.tim
var TIM = app.imInit.TIM
let watchvoiceRoom
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: '', //控制聊天区域文字滚动
    newMessages: [], // 轮询最新消息
    //主持人
    voiceRoom: {
      info: null, //个人信息   放在voiceRoom  里面
      muted: false, //muted   boolean	false	否	是否静音  
      enableMic: true, // 主持人 enable-mic	boolean	true	否	开启或关闭麦克风 
      soundMode: 'speaker', // sound-mode  string	speaker	扬声器  ear	否	声音输出方式
      enableCamera: false, //摄像头
    },
    roomId: null, //roomId  有roomId  才说明是用户从点击跳过来的   //   房主的roomid  从voiceRoom.voiceRoom 里面拿
    //观众进入直播间时候 获取到的房间信息和地址  只有观众方有
    innerUser: {
      info: null, //个人信息   放在voiceRoom  里面
      muted: false, //muted   boolean	false	否	是否静音  
      enableMic: true, // 观众 enable-mic	boolean	true	否	开启或关闭麦克风 
      soundMode: 'speaker', // sound-mode  string	speaker	扬声器  ear	否	声音输出方式
      enableCamera: false, //摄像头
      roomInfo: null, //图片和推拉流信息
    }, //观众
    value: null, //聊天输入框内容
    showApplying: false, //是否展示连麦列表弹出框
    applying: 0, //申请连麦的人的个数
    applyingList: [], //正在申请连麦的用户id列表
    applyingMemberList: [], //正在申请连麦的用户详情列表
  },
  //滚动
  upper(e) {
    // console.log(e)
  },
  lower(e) {
    // console.log(e)
  },
  // 到底部去
  toButton() {
    let that = this
    // 到底部去
    let query = wx.createSelectorQuery();
    query.select('.content').boundingClientRect(rect => {
      let clientHeight = rect.height;
      let clientWidth = rect.width;
      let ratio = 750 / clientWidth;
      let height = clientHeight * ratio;
      // console.log(height);
      that.setData({
        scrollTop: height + 100 + 'rpx'
      })
    }).exec();
  },
  // 退出直播间
  userOut() {
    var postObj = {
      url: '/room/quit',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: roomId
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('退出直播间', res)
      // console.log(res.data.data)

    }).catch(err => {
      console.log('退出直播间', err)
    })
  },
  //onClose  关闭正在申请连麦的用户列表
  onCloseApplying() {
    let that = this
    that.setData({
      showApplying: false, //是否展示连麦列表弹出框
      // applying: 0, //申请连麦的人的个数
      applyingList: [], //正在申请连麦的用户id列表
      applyingMemberList: [], //正在申请连麦的用户详情列表
    })
  },
  // 获取正在申请连麦的用户列表
  getLineApplying() {
    let that = this
    console.log(this.data.voiceRoom);
    var postObj = {
      url: '/room/line/applying/get',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: that.data.voiceRoom.voiceRoom.roomInfo.roomId
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('获取正在申请连麦的用户列表', res)
      let list = res.data.data //userId  列表  


      let promise = tim.getGroupMemberProfile({
        groupID: that.data.voiceRoom.voiceRoom.roomInfo.roomId.toString(),
        userIDList: list, // 请注意：即使只拉取一个群成员的资料，也需要用数组类型，例如：userIDList: ['user1']
        memberCustomFieldFilter: ['group_member_custom'], // 筛选群成员自定义字段：group_member_custom
      });
      promise.then(function (imResponse) {
        console.log(' 群成员列表', imResponse.data.memberList); // 群成员列表
        let memberList = imResponse.data.memberList
        that.setData({
          applyingList: list, //正在申请连麦的用户列表
          showApplying: true, //展示
          applyingMemberList: memberList, //正在申请连麦的用户详情列表
        })
      }).catch(function (imError) {
        console.warn('getGroupMemberProfile error:', imError);
      });




    }).catch(err => {
      console.log('获取正在申请连麦的用户列表', err)
    })
  },
  // 申请连麦接口
  lineApply() {
    var postObj = {
      url: '/room/line/apply',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: this.data.roomId,
        roomType: 'voice'
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('申请连麦接口', res)
      // console.log(res.data.data)

    }).catch(err => {
      console.log('申请连麦接口', err)
    })
  },
  // 用户取消连麦申请
  lineApplyCancel() {
    var postObj = {
      url: '/room/line/apply',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: roomId,
        roomType: 'voice'
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('用户取消连麦申请', res)
      // console.log(res.data.data)
    }).catch(err => {
      console.log('用户取消连麦申请', err)
    })
  },
  // 主持人处理连麦申请
  lineDealApply(event) {
    let that = this
    let item = event.currentTarget.dataset.item
    let decision = event.currentTarget.dataset.decision
    let index = event.currentTarget.dataset.index
    let roomId = that.data.voiceRoom.voiceRoom.roomInfo.roomId
    let applying = Number(that.data.applying)


    var postObj = {
      url: '/room/line/dealApply',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: roomId,
        applyUserId: item.userID, //是	string	申请连麦的用户id
        decision: decision, //	是	string	主持人处理结果，枚举，同意则"agree"；拒绝则"refuse"
      }
    }
    app.request.noLoginRequest(postObj).then(res => {

      that.setData({
        applying: applying >= 1 ? applying - 1 : 0
      })

      if (decision == 'agree') {
        console.log('agree主持人处理连麦申请同意', res)
      }

      if (decision == 'refuse') {
        console.log('refuse主持人处理连麦申请拒绝', res)
      }
      that.onCloseApplying()
    }).catch(err => {
      console.log('err主持人处理连麦', err)
    })

    //  0: e
    //   userID: "838804127"
    //   avatar: ""
    //   nick: "小杨"
    //   role: "Member"
    //   joinTime: 1604481745
    //   lastSendMsgTime: ""
    //   nameCard: ""
    //   muteUntil: 0
    //   memberCustomField: []
    //   __proto__: Object
    //   length: 1
    //   __proto__: Array(0) 
  },
  // 获取连麦中的用户接口
  lineLiningGet() {
    let that = this
    let roomId = that.data.voiceRoom.voiceRoom.roomInfo.roomId
    var postObj = {
      url: '/room/line/lining/get',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: roomId,
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('获取连麦中的用户接口', res)
      // console.log(res.data.data)
    }).catch(err => {
      console.log('获取连麦中的用户接口', err)
    })
  },
  // 用户退出连麦
  lineQuitLining() {
    var postObj = {
      url: '/room/line/quitLining',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: roomId
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('用户退出连麦', res)
      // console.log(res.data.data)
    }).catch(err => {
      console.log('用户退出连麦', err)
    })
  },
  // 观众进入直播间
  userIn(roomId) {
    var postObj = {
      url: '/room/join/viewer',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId'),
        roomId: roomId
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('观众进入直播间', res)
      // console.log(res.data.data)
      this.setData({
        ['innerUser.roomInfo']: res.data.data //观众进入直播间时候 获取到的房间信息和地址  只有观众方有
      })
    }).catch(err => {
      console.log('观众进入直播间', err)
    })
  },
  // 切换我的声音  房主
  toggleMic() {
    var enableMic = this.data.voiceRoom.enableMic
    if (enableMic == true) {
      this.setData({
        ['voiceRoom.enableMic']: false
      })
      wx.showToast({
        icon: "none",
        title: "关闭麦克风"
      })
    }
    if (enableMic == false) {
      this.setData({
        ['voiceRoom.enableMic']: true
      })
      wx.showToast({
        icon: "none",
        title: "打开麦克风"
      })
    }
  },
  // // 切换我的声音  用户 toggleMicUser 
  toggleMicUser() {
    var enableMic = this.data.innerUser.enableMic
    if (enableMic == true) {
      this.setData({
        ['innerUser.enableMic']: false
      })
      wx.showToast({
        icon: "none",
        title: "关闭麦克风"
      })
    }
    if (enableMic == false) {
      this.setData({
        ['innerUser.enableMic']: true
      })
      wx.showToast({
        icon: "none",
        title: "打开麦克风"
      })
    }
  },
  // push
  statechangepush(e) {
    console.log('live-pusher', e);
    wx.showToast({
      icon: "none",
      title: e.detail.message
    })
    console.log(e.detail.message);
  },
  // player
  statechangeplayer(e) {
    wx.showLoading({
      title: '等待连接中...',
    })
    console.log('live-player', e);
    wx.showToast({
      icon: "none",
      title: e.detail.message
    })
    console.log(e.detail.message);

    if (e.detail.code == -2301) {
      wx.hideLoading()
      wx.showToast({
        icon: "none",
        title: "对方离线/未上线",
        success: () => {
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      })
    }
  },
  // 个人中心页面，获取个人数据
  getInfo() {
    console.log('获取个人数据111')
    var postObj = {
      url: '/user/info/get',
      method: 'POST',
      data: {
        token: wx.getStorageSync('token'),
        userId: wx.getStorageSync('userId')
      }
    }
    app.request.noLoginRequest(postObj).then(res => {
      console.log('获取个人数据', res)
      // console.log(res.data.data)
      this.setData({
        [`voiceRoom.info`]: res.data.data
      })
    }).catch(err => {
      // console.log('获取个人数据', err)
    })
  },
  // 内容change
  onChangevalue(event) {
    // event.detail 为当前输入的值
    this.setData({
      value: event.detail
    })
  },
  //sendValue  发送内容
  sendValue() {
    let that = this
    let roomId = that.data.roomId // //roomId  有roomId  才说明是用户从点击跳过来的   //   房主的roomid  从voiceRoom.voiceRoom 里面拿
    // 普通用户  游客
    if (!!roomId) {
      // 发送文本消息，Web 端与小程序端相同
      // 1. 创建消息实例，接口返回的实例可以上屏
      let message = tim.createTextMessage({
        to: roomId.toString(),
        conversationType: TIM.TYPES.CONV_GROUP,
        payload: {
          text: that.data.value
        }
      });
      // 2. 发送消息
      let promise = tim.sendMessage(message);
      promise.then(function (imResponse) {
        // 发送成功
        console.log(imResponse);
        var message = imResponse.data.message
        message.nick = "我"
        var newMessages = that.data.newMessages
        that.setData({
          newMessages: [...newMessages, ...[message]]
        })
        // console.log('that.data.newMessages', that.data.newMessages);
        that.setData({
          value: ''
        })
        // 到底部去
        that.toButton()
      }).catch(function (imError) {
        // 发送失败
        console.warn('sendMessage error:', imError);
      });
    } else {
      // 房主
      let voiceRoom = this.data.voiceRoom.voiceRoom //voiceRoom.roomInfo.roomId
      let roomId = voiceRoom.roomInfo.roomId
      // 发送文本消息，Web 端与小程序端相同
      // 1. 创建消息实例，接口返回的实例可以上屏
      let message = tim.createTextMessage({
        to: roomId.toString(),
        conversationType: TIM.TYPES.CONV_GROUP,
        priority: TIM.TYPES.MSG_PRIORITY_HIGH,
        payload: {
          text: that.data.value
        }
      });
      // 2. 发送消息
      let promise = tim.sendMessage(message);
      promise.then(function (imResponse) {
        // 发送成功
        console.log(imResponse);
        var message = imResponse.data.message
        message.nick = "我"
        var newMessages = that.data.newMessages
        that.setData({
          newMessages: [...newMessages, ...[message]]
        })
        // console.log('that.data.newMessages', that.data.newMessages);
        that.setData({
          value: ''
        })
        // 到底部去
        that.toButton()
      }).catch(function (imError) {
        // 发送失败
        console.warn('sendMessage error:', imError);
      });
    }
  },
  // 监听新的群消息消息
  watchMessageGroup() {
    let that = this
    watchvoiceRoom = function (event) {
      // 收到群组列表更新通知，可通过遍历 event.data 获取群组列表数据并渲染到页面
      // event.name - TIM.EVENT.GROUP_LIST_UPDATED
      // event.data - 存储 Group 对象的数组 - [Group]
      console.log('watchMessageGroup 监听群组新消息', event);

      var data = event.data
      if (data.length > 0) {
        data.forEach((items, i) => {
          if (!!items.payload.extension) items.payload.extension = JSON.parse(items.payload.extension)
          if (items.payload.data == "normal") {
            console.log("用户进入 normal", items.payload.extension);
            var newMessages = that.data.newMessages
            that.setData({
              newMessages: [...newMessages, ...[items.payload]]
            })
          }
          if (!!items.payload.text) {
            console.log("TIMTextElem");
            var newMessages = that.data.newMessages
            that.setData({
              newMessages: [...newMessages, ...[items]]
            })
          }
          if (items.payload.data == "welcome") {
            console.log("用户普通欢迎 welcome", items.payload.extension);
            var newMessages = that.data.newMessages
            that.setData({
              newMessages: [...newMessages, ...[items.payload]]
            })
          }
          if (items.payload.data == "welcome_animate") {
            console.log("用户进入动画特效欢迎 welcome_animate", items.payload.extension);
          }
          if (items.payload.data == "system") {
            if (items.payload.extension.code == 101) {
              console.log("房间观众人数变化    system", items.payload.extension);
            }
            if (items.payload.extension.code == 103) {
              console.log("解散房间    system", items.payload.extension);
              wx.navigateBack()
            }
            if (items.payload.extension.code == 107) {
              console.log("关注通知    system", items.payload.extension);
            }
            if (items.payload.extension.code == 202) {
              console.log("申请连麦人数变化    system", items.payload.extension);
              var applying = items.payload.extension.data
              that.setData({
                applying: applying
              })
            }
            if (items.payload.extension.code == 900) {
              console.log("房间被管理员强制下播    system", items.payload.extension);
            }
          }
        })
      }
      that.toButton()
    }
    tim.on(TIM.EVENT.MESSAGE_RECEIVED, watchvoiceRoom);
  },
  // // 创建好友工作群
  createGroup(userID, roomName, roomId) {
    let that = this
    let promise = tim.createGroup({
      type: TIM.TYPES.GRP_PUBLIC,
      name: roomName,
      groupID: roomId.toString(),
      joinOption: TIM.TYPES.JOIN_OPTIONS_FREE_ACCESS,
      memberList: [{
        userID: userID.toString()
      }]
      // 如果填写了 memberList，则必须填写 userID
    });
    promise.then(function (imResponse) { // 创建成功
      console.log('创建的群的资料', imResponse.data.group); // 创建的群的资料
      // that.onSdkReady()
    }).catch(function (imError) {
      console.warn('创建群组失败的相关信息createGroup error:', imError); // 创建群组失败的相关信息
    });
  },
  // 添加群成员  只有 App 管理员可以邀请他人入群，且无需被邀请人同意，直接将其拉入群组中
  addGroupMember(roomId, userId) {
    //     TIM.TYPES.GRP_WORK（好友工作群）：任何群成员都可邀请他人加群，且无需被邀请人同意，直接将其拉入群组中。
    // TIM.TYPES.GRP_PUBLIC（陌生人社交群）/ TIM.TYPES.GRP_MEETING（临时会议群）：只有 App 管理员可以邀请他人入群，且无需被邀请人同意，直接将其拉入群组中。
    // TIM.TYPES.GRP_AVCHATROOM（直播群）：不允许任何人邀请他人入群（包括 App 管理员）。
    let promise = tim.addGroupMember({
      groupID: roomId,
      userIDList: userId,
    });
    promise.then(function (imResponse) {
      console.log('添加成功的群成员 userIDList', imResponse.data.successUserIDList); // 添加成功的群成员 userIDList
      console.log('添加失败的群成员 userIDList', imResponse.data.failureUserIDList); // 添加失败的群成员 userIDList
      console.log('已在群中的群成员 userIDList', imResponse.data.existedUserIDList); // 已在群中的群成员 userIDList
      console.log('添加后的群组信息', imResponse.data.group); // 添加后的群组信息
    }).catch(function (imError) {
      console.warn('addGroupMember error:', imError); // 错误信息
    });
  },
  // 群主可调用该接口解散群组。
  dismissGroup(roomId) {
    let promise = tim.dismissGroup(roomId.toString());
    promise.then(function (imResponse) { // 解散成功
      console.log(imResponse.data.groupID); // 被解散的群组 ID
    }).catch(function (imError) {
      console.warn('dismissGroup error:', imError); // 解散群组失败的相关信息
    });
  },
  // 用户退出群组。 删除群成员。群主可移除群成员。  
  deleteGroupMember(roomId, userId) {
    // let promise = tim.deleteGroupMember({
    //   groupID: roomId,
    //   userIDList:userId ,
    //   reason: '用户退出！'
    // });
    // promise.then(function (imResponse) {
    //   console.log(imResponse.data.group); // 删除后的群组信息
    //   console.log(imResponse.data.userIDList); // 被删除的群成员的 userID 列表
    // }).catch(function (imError) {
    //   console.warn('deleteGroupMember error:', imError); // 错误信息
    // });
    let promise = tim.quitGroup(roomId);
    promise.then(function (imResponse) {
      console.log('退出成功的群 ID', imResponse.data.groupID); // 退出成功的群 ID
    }).catch(function (imError) {
      console.warn(' // 退出群组失败的相关信息 quitGroup error:', imError); // 退出群组失败的相关信息
    });
  },
  // 用户申请加群的接口，申请加入某个群组时调用。
  joinGroup() {
    let roomId = this.data.roomId.toString()
    let promise = tim.joinGroup({
      groupID: this.data.roomId.toString(),
      type: TIM.TYPES.GRP_AVCHATROOM
    });
    promise.then(function (imResponse) {
      switch (imResponse.data.status) {
        case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
          break;
        case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
          console.log(imResponse.data.group); // 加入的群组资料
          break;
        case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
          break;
        default:
          break;
      }
    }).catch(function (imError) {
      console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let voiceRoom = wx.getStorageSync('voiceRoom')
    console.log(" 主持人  voiceRoom", voiceRoom);


    let roomId = options.roomId //roomId  有roomId  才说明是用户从点击跳过来的   //   房主的roomid  从voiceRoom.voiceRoom 里面拿

    this.setData({
      ['voiceRoom.voiceRoom']: voiceRoom,
    })


    // 主持人进入直播间
    if (!!voiceRoom) {
      this.getInfo()
      if (!!voiceRoom.roomInfo.roomName) {
        wx.setNavigationBarTitle({
          title: voiceRoom.roomInfo.roomName,
        })
      }
      this.createGroup(voiceRoom.roomInfo.userId, voiceRoom.roomInfo.roomName, voiceRoom.roomInfo.roomId) //群主创建房间
    }




    if (!!roomId) {
      // 观众进入直播间
      this.userIn(roomId)
      this.setData({
        roomId: roomId
      })
      var arr = []
      arr[0] = wx.getStorageSync('userId').toString()
      console.log(roomId.toString(), arr);

      // this.addGroupMember(roomId,arr)
      this.joinGroup()
    }

    this.watchMessageGroup()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.onCloseApplying()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("onUnloadonUnloadonUnloadonUnloadonUnloadonUnload");
    wx.removeStorage({
      key: 'voiceRoom'
    })
    wx.removeStorageSync({
      key: 'voiceRoom'
    })


    let roomId = this.data.roomId //roomId  有roomId  才说明是用户从点击跳过来的   //   房主的roomid  从voiceRoom.voiceRoom 里面拿
    // 主持人退出直播间
    let voiceRoom = this.data.voiceRoom.voiceRoom
    let userId = wx.getStorageSync('userId')
    // 用户退出直播间
    if (!!roomId) {
      console.log('userId, roomId', userId, roomId);
      var arr = []
      arr[0] = userId.toString()

      console.log('roomId, arr', roomId, arr);
      this.deleteGroupMember(roomId, arr)

    }


    if (!!voiceRoom) {
      console.log('voiceRoom.roomInfo.roomId', voiceRoom.roomInfo.roomId);

      this.dismissGroup(voiceRoom.roomInfo.roomId)
    }




    tim.off(TIM.EVENT.MESSAGE_RECEIVED, watchvoiceRoom);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})